package org.hxzon.demo.netty;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureProgressListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.DefaultFileRegion;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.FileRegion;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class FileDownloadServerHandler extends SimpleChannelHandler {
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		Channel ch = e.getChannel();

		ChannelBuffer buffer =ChannelBuffers.buffer(8);
		try {
			File file = new File("D:/export/1_All_Misc_Packets_tcp_2010_10_28_17-9-18.pcap");
			RandomAccessFile raf= new RandomAccessFile(file, "r");
			long fileLength = raf.length();
			System.out.println(fileLength);
			ChannelFuture writeFuture;
			buffer.writeLong(fileLength);
			ch.write(buffer);
//			writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
//			writeFuture = ch.write(new ChunkedNioFile(file,16*1024));
			final FileRegion region =
                new DefaultFileRegion(raf.getChannel(), 0, fileLength);
            writeFuture = ch.write(region);
            writeFuture.addListener(new ChannelFutureProgressListener() {
                public void operationComplete(ChannelFuture future) {
                    region.releaseExternalResources();
                }

                public void operationProgressed(
                        ChannelFuture future, long amount, long current, long total) {
                }
            });
			// e.getChannel().write(channel);
			// e.getChannel().write((int)data.length);
			// e.getChannel().write(data);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		ChannelBuffer channel = (ChannelBuffer) e.getMessage();

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		e.getCause().printStackTrace();
		e.getChannel().close();
	}
}